package cn.edu.xmist.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.LogManager;
import java.util.logging.Logger;

/**
 * @author zhongjinbin (jinbin.zhong@nascent.cn)
 * @version 1.0.0
 * @date 2021/1/8 13:46
 * @description 1.创建Callable接口的实现类，并实现call()方法，然后创建该实现类的实例（从java8开始可以直接使用Lambda表达式创建Callable对象）
 * 2.使用FutureTask类来包装Callable对象，该FutureTask对象封装了Callable对象的call()方法的返回值
 * 3.使用FutureTask类来包装Callable对象，该FutureTask对象封装了Callable对象的call()方法的返回值 4.
 * 4.调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
 */
public class CallableAndFuture2Test {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<Integer> results = executor.submit(task);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("主线程执行任务");

        try {
            System.out.println("task运行的结果" + results.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("所有任务执行完成");
    }

    static class Task implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            System.out.println("子线程在进行计算");
            Thread.sleep(3000);
            int sum = 0;
            for (int i = 0; i < 100; i++) {
                sum += i;
            }
            return sum;
        }
    }
}
